import os
import tkinter as tk
from tkinter import scrolledtext
import itchat 
from itchat.content import TEXT 
import jieba 
import requests

# 设置 DeepSeek API 相关信息
DEEPSEEK_API_KEY = "your_deepseek_api_key"
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"

# 调用 DeepSeek API 获取回复
def get_chatgpt_reply(text):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "user", "content": text}
        ]
    }
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        return result["choices"][0]["message"]["content"]
    except requests.RequestException as e:
        print(f"调用 DeepSeek API 出错: {e}")
        return "抱歉，暂时无法回复。"

# 处理用户输入并显示回复
def send_message():
    user_input = input_box.get()
    if user_input:
        words = jieba.lcut(user_input)
        segmented_text = " ".join(words)

        chat_box.insert(tk.END, f"你: {user_input}\n")

        reply = get_chatgpt_reply(segmented_text)

        chat_box.insert(tk.END, f"机器人: {reply}\n")

        input_box.delete(0, tk.END)

# 自动回复微信消息
@itchat.msg_register(TEXT)
def text_reply(msg):
    words = jieba.lcut(msg.text)
    segmented_text = " ".join(words)

    reply = get_chatgpt_reply(segmented_text)

    chat_box.insert(tk.END, f"{msg.fromUserName}: {msg.text}\n")
    chat_box.insert(tk.END, f"机器人: {reply}\n")

    return reply

# 创建主窗口
root = tk.Tk()
root.title("微信机器人聊天框")

# 创建聊天框
chat_box = scrolledtext.ScrolledText(root, width=50, height=20)
chat_box.pack(pady=10)

# 创建输入框
input_box = tk.Entry(root, width=40)
input_box.pack(pady=5)

# 创建发送按钮
send_button = tk.Button(root, text="发送", command=send_message)
send_button.pack(pady=5)

# 重写 itchat 的 check_login 方法以打印 XML 数据
# 暂时注释掉自定义的 check_login 方法
# original_check_login = itchat.check_login
#
# def custom_check_login(*args, **kwargs):
#     result = original_check_login(*args, **kwargs)
#     s = itchat.instanceList[0].s
#     loginInfo = itchat.instanceList[0].loginInfo
#     r = s.get(loginInfo['url'], params=loginInfo['params'])
#     print("服务器返回的 XML 数据:")
#     print(r.text)  # 打印服务器返回的 XML 数据
#     return result
#
# itchat.check_login = custom_check_login

# 登录微信
itchat.auto_login(hotReload=True)

# 恢复原始的 check_login 方法
itchat.check_login = original_check_login

# 启动微信消息监听
import threading
threading.Thread(target=itchat.run).start()

# 运行主循环
root.mainloop()

